﻿using System;
using Microsoft.Phone.Controls;
using Microsoft.Devices;
using System.Windows.Threading;
using System.Collections.ObjectModel;
using System.Windows.Navigation;
using WP7_Barcode_Library;
using System.Windows.Media.Imaging;
using System.Threading;
using Microsoft.Phone.Shell;
using System.Windows;
using System.Net;
using System.IO;

using com.google.zxing;
using com.google.zxing.oned;
using com.google.zxing.common;

namespace SF
{
    public partial class MainPage : PhoneApplicationPage
    {
        private PhotoCamera _photoCamera;
        private Code128Reader _sfReader;
        private PhotoCameraLuminanceSource _luminance;

        public MainPage()
        {
            InitializeComponent();
        }

        private void Scan()
        {
            tbResult.Text = "";
            tbWebResult.Text = "";
            _photoCamera.Focus();
        }

        private void Search()
        {
            string yundan = tbResult.Text;
            Uri url= new Uri("http://api.kuaidi100.com/apione?com=shunfeng&nu="+ yundan +"&show=3");
            WebClient wb = new WebClient();
            wb.OpenReadAsync(url);
            wb.OpenReadCompleted += wb_OpenReadCompleted;
        }

        void wb_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            using (StreamReader sr = new StreamReader(e.Result))
            {
                tbWebResult.Text =  sr.ReadToEnd();
            }  
        }


        #region Camera
        private void InitCam()
        {
            _photoCamera = new PhotoCamera();
            _photoCamera.Initialized += OnPhotoCameraInitialized;
            _photoCamera.AutoFocusCompleted += OnPhotoAutoFocusCompleted;
            _photoCamera.CaptureCompleted += OnPhotoCameraCaptureCompleted;
            _previewVideo.SetSource(_photoCamera);
            CameraButtons.ShutterKeyHalfPressed += (o, arg) => _photoCamera.Focus();
            WP7BarcodeManager.ScanMode = com.google.zxing.BarcodeFormat.CODE_128;
        }

        private void OnPhotoCameraInitialized(object sender, CameraOperationCompletedEventArgs e)
        {
            _photoCamera.FlashMode = FlashMode.Off;
            int width = Convert.ToInt32(_photoCamera.PreviewResolution.Width);
            int height = Convert.ToInt32(_photoCamera.PreviewResolution.Height);
            _luminance = new PhotoCameraLuminanceSource(width, height);
            _sfReader = new Code128Reader();
        }

        private void OnPhotoAutoFocusCompleted(object sender, CameraOperationCompletedEventArgs e)
        {
            _photoCamera.CaptureImage();
        }

        private void OnPhotoCameraCaptureCompleted(object sender, CameraOperationCompletedEventArgs e)
        {
            ScanPreviewBuffer();
        }
        #endregion


        #region override OnNavigatedTo

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            InitCam();
            base.OnNavigatedTo(e);
        }

        #endregion

        #region ApplicationBarIconButton_Click
        private void ApplicationBarIconButton_Click(object sender, EventArgs e)
        {
            Scan();
        }

        private void ApplicationBarIconButton_Click_1(object sender, EventArgs e)
        {
            Search();
        } 
        #endregion


        private void ScanPreviewBuffer()
        {
            Result result;
            try
            {
                _photoCamera.GetPreviewBufferY(_luminance.PreviewBufferY);
                var binarizer = new HybridBinarizer(_luminance);
                var binBitmap = new BinaryBitmap(binarizer);
                result = _sfReader.decode(binBitmap);
                Dispatcher.BeginInvoke(() => DisplayResult(result.Text));
            }
            catch(Exception ex)
            {
                Dispatcher.BeginInvoke(() => DisplayResult("无法识别，请重新扫描！")); 
            }
        }

        private void DisplayResult(string text)
        {
            tbResult.Text = text;
        }
        
    }
}